package com.jsoft.controller;

import com.alibaba.fastjson.JSON;
import com.jsoft.entity.Enterprise;
import com.jsoft.entity.MyVoucher;
import com.jsoft.entity.TransferMessage;
import com.jsoft.entity.Voucher;
import com.jsoft.service.*;
import com.jsoft.service.impl.*;
import com.jsoft.util.IsNumeric;
import com.jsoft.util.Message;
import com.jsoft.util.ResultUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author:sha
 * @email:o68o4741@163.com
 * @date:2023/2/20
 */
@WebServlet("*.tra")
@MultipartConfig
public class TransferMessageController extends HttpServlet {
    private static TransferMessageService transferMessageService = new TransferMessageServiceImpl();
    private static VoucherService voucherService = new VoucherServiceImpl();
    private static TransferService transferService = new TransferServiceImpl();
    private static EnterpriseService enterpriseService = new EnterpriseServiceImpl();
    private static MyVoucherService myVoucherService = new MyVoucherServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        String servletPath = request.getServletPath();
        String methodName = servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length() - 4);

        try {
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    protected void getTransferMessage(HttpServletRequest request, HttpServletResponse response){
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String idStr = request.getParameter("id");
        Integer id = Integer.parseInt(idStr);
        try {
            TransferMessage transferMessage = transferMessageService.getTransferMessage(id);
            out.write(JSON.toJSONString(new ResultUtil("transferMessage", transferMessage)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            out.close();
        }
    }

    protected void insertTransferMessage(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        /**
         * 面板显示的红色金额 showAmount
         */
        String amountStr2 = request.getParameter("showAmount");
        Double showAmount = Double.parseDouble(amountStr2);
        String selectEnterprise = request.getParameter("selectEnterprise");

        /**
         * 输入的金额 inputAmount
         */
        String amountStr1 = request.getParameter("inputAmount");
        String amountStr1Trim = amountStr1.trim();
        String remark = request.getParameter("remark");
        if (selectEnterprise == null || selectEnterprise.equals("")) {
            out.write(JSON.toJSONString(new Message(601, "收单企业为空。添加失败，请重试！")));
            return;
        } else if (amountStr1Trim == null || amountStr1Trim.equals("")) {
            out.write(JSON.toJSONString(new Message(602, "转让金额不能为空。添加失败，请重试！")));
            return;
        } else if (!IsNumeric.isNumeric(amountStr1Trim)){
            out.write(JSON.toJSONString(new Message(604, "转让金额不合法。添加失败，请重试！")));
            return;
        } else {
            Double inputAmount = Double.parseDouble(amountStr1Trim);
            if (inputAmount - showAmount > 0) {
                out.write(JSON.toJSONString(new Message(603, "转让金额大于凭证金额。添加失败，请重试！")));
                out.close();
                return;
            }
            /**
             * 转让金额等于凭证金额
             */
            else if (inputAmount.equals(showAmount)) {
                /**
                 * 拿到单号id
                 */
                String idStr = request.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                /**
                 * 利用前台反射得信息拿到voucher中的信息
                 */
                Voucher voucherById = null;
                Integer enterpriseId = null;
                /**
                 * 通过voucher对象中的信息添加一条信息到transfer列表中
                 */
                try {
                    voucherById = voucherService.getVoucherById(id);
                    out.write(JSON.toJSONString(new ResultUtil("voucherById", voucherById)));
                    enterpriseId = enterpriseService.getEnterpriseId(selectEnterprise);
                    transferService.insertTransfer(voucherById, inputAmount, remark, enterpriseId);
                    /**
                     * 将Voucher表中对应id的status修改为“已签收”
                     */
                    voucherService.updateStatus(id);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    out.close();
                }
            }else{
                /**
                 * 转让金额小于凭证金额，需要生成一条transfer记录，
                 * 还要将voucher表中的原数据对应的status修改为“已签收”，
                 * 还要生成一条新的voucher记录
                 */
                /**
                 * 拿到单号id
                 */
                String idStr = request.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                Voucher voucherById = null;
                Integer enterpriseId = null;
                /**
                 * 利用前台反射得信息拿到voucher中的信息
                 * 通过voucher对象中的信息添加一条信息到transfer列表中
                 */
                try {
                    voucherById = voucherService.getVoucherById(id);
                    out.write(JSON.toJSONString(new ResultUtil("voucherById", voucherById)));
                    enterpriseId = enterpriseService.getEnterpriseId(selectEnterprise);
                    transferService.insertTransfer(voucherById, inputAmount, remark, enterpriseId);
                    /**
                     * 将Voucher表中对应id的status修改为“已签收”
                     */
                    voucherService.updateStatus(id);
                    /**
                     * 算出差值 double
                     * 生成一条新的voucher记录
                     */
                    double balance = showAmount - inputAmount;
                    voucherService.insertVoucher(voucherById,id,balance);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                finally {
                    out.close();
                }

            }
        }
    }

    protected void getSelect(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        /**
         * 拿到单号id
         */
        String idStr = request.getParameter("id");
        Integer id = Integer.parseInt(idStr);
        try {
            /**
             *根据voucher的id获取其企业id，就是enterprise_id.
             */
            Voucher voucherById = voucherService.getVoucherById(id);
            Integer enterpriseId = voucherById.getEnterpriseId();
            List<Enterprise> enterprisesName = enterpriseService.listOtherEnterpriseName(enterpriseId);
            out.write(JSON.toJSONString(new ResultUtil("enterprisesName", enterprisesName)));
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            out.close();
        }
    }

    protected void getMyEnterprise(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        /**
         * 拿到单号id
         */
        String idStr = request.getParameter("id");
        Integer id = Integer.parseInt(idStr);
        try {
            Voucher voucherById = voucherService.getVoucherById(id);
            Integer enterpriseId = voucherById.getEnterpriseId();
            String name = enterpriseService.getName(enterpriseId);
//            String socialUniformCode = enterpriseService.getSocialUniformCode(name);
            out.write(JSON.toJSONString(new ResultUtil("name", name)));
//            out.write(JSON.toJSONString(new ResultUtil("socialUniformCode",socialUniformCode)));
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            out.close();
        }
    }

    protected void getSocialUniformCode(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        /**
         * 拿到单号id
         */
        String idStr = request.getParameter("id");
        Integer id = Integer.parseInt(idStr);
        try {
            Voucher voucherById = voucherService.getVoucherById(id);
            Integer enterpriseId = voucherById.getEnterpriseId();
            String name = enterpriseService.getName(enterpriseId);
            String socialUniformCode = enterpriseService.getSocialUniformCode(name);
            out.write(JSON.toJSONString(new ResultUtil("socialUniformCode", socialUniformCode)));
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            out.close();
        }
    }

    protected void getSocialUniformCodeFromName(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String name = request.getParameter("name");
        try {
            String socialUniformCode = enterpriseService.getSocialUniformCode(name);
            out.write(JSON.toJSONString(new ResultUtil("socialUniformCode", socialUniformCode)));
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            out.close();
        }
    }
    protected void getRemainTime(HttpServletRequest request, HttpServletResponse response){
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        /**
         * 获取传过来的到期日期的时间戳
         */
        String expiryTimeStr = request.getParameter("expiryTime");
        long expiryTime = Long.parseLong(expiryTimeStr);
        /**
         * 设值日期格式,同时获取当前时间戳
         */
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = dateFormat.format(date);
        long nowTime = 0;
        try {
            Date date1 = dateFormat.parse(nowDate);
             nowTime = date1.getTime();
            /**
             * 做将传过来的时间戳和当前精确到 “天” 的时间戳做差值
             */
            long sub = expiryTime - nowTime;
            long dateNumber = sub / 1000 / 60 / 60 / 24;
            out.write(JSON.toJSONString(new ResultUtil("dateNumber",dateNumber)));
            out.flush();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }finally {
            out.close();
        }


    }
    protected void getVoucherId(HttpServletRequest request, HttpServletResponse response){
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String enterpriseIdStr = request.getParameter("enterpriseId");
        Integer enterpriseId = Integer.parseInt(enterpriseIdStr);
        try {
            List<MyVoucher> idAndStatus = myVoucherService.getIdAndStatus(enterpriseId);
            for (MyVoucher andStatus : idAndStatus) {
            }
            List arrVoucherIds = new ArrayList();
            for (MyVoucher myVoucher : idAndStatus) {
                Integer id = myVoucher.getId();
                arrVoucherIds.add(id);
            };
            out.write(JSON.toJSONString(new ResultUtil("arrVoucherIds",arrVoucherIds)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            out.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
